package com.fh.common.copy;

import java.lang.reflect.Field;
import java.util.List;

import com.fh.common.util.ReflectUtils;

/**
 * @author Qiu,Junda
 * @date 2019年8月4日
 * @description
 */
public class BeanUtils {

	/**
	 * 复制属性
	 * 
	 * @author Qiu,Junda
	 * @date 2019年8月4日
	 * @description
	 * @param originBean
	 * @param targetBean
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	public static void copy(Object originBean, Object targetBean, CopyType copyType)
			throws IllegalArgumentException, IllegalAccessException {
		List<Field> origin = ReflectUtils.getClassFieldsByAnnotation(originBean, CopyField.class);
		for (Field orginField : origin) {
			CopyField copyField = orginField.getAnnotation(CopyField.class);
			switch (copyType) {
			case ADD:
				if (copyField.add()) {
					copy(orginField, originBean, targetBean);
				}
				break;
			case UPDATE:
				if (copyField.update()) {
					copy(orginField, originBean, targetBean);
				}
				break;
			default:
				break;
			}
		}
	}

	private static void copy(Field orginField, Object originBean, Object targetBean)
			throws IllegalArgumentException, IllegalAccessException {
		orginField.setAccessible(true);
		Object value = orginField.get(originBean);
		Field targetField = ReflectUtils.getClassFieldByName(targetBean.getClass(), orginField.getName());
		targetField.setAccessible(true);
		targetField.set(targetBean, value);
		orginField.setAccessible(false);
		targetField.setAccessible(false);
	}
}
